package city.spring.modules.system.service.impl;

import city.spring.modules.system.entity.DataDictionaryEntity;
import city.spring.modules.system.entity.DataDictionaryValueEntity;
import city.spring.modules.system.repository.DataDictionaryRepository;
import city.spring.modules.system.repository.DataDictionaryValueRepository;
import city.spring.modules.system.service.DataDictionaryValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据字典值信息 Service
 *
 * @author HouKunLin
 * @date 2020/3/26 0026 23:38
 */
@Service
public class DataDictionaryValueServiceImpl extends ServiceImpl<DataDictionaryValueRepository, DataDictionaryValueEntity> implements DataDictionaryValueService {
    private final DataDictionaryRepository dictionaryRepository;

    public DataDictionaryValueServiceImpl(DataDictionaryRepository dictionaryRepository) {
        this.dictionaryRepository = dictionaryRepository;
    }

    @Override
    public void saveDataDictionaryValue(DataDictionaryValueEntity entity) {
        checkSystemDataDictionary(entity);
        save(entity);
    }

    @Override
    public void updateDataDictionaryValue(DataDictionaryValueEntity entity) {
        checkSystemDataDictionary(entity);
        lambdaUpdate()
                .set(DataDictionaryValueEntity::getDictionaryId, entity.getDictionaryId())
                .set(DataDictionaryValueEntity::getLabel, entity.getLabel())
                .set(DataDictionaryValueEntity::getValue, entity.getValue())
                .set(DataDictionaryValueEntity::getRemarks, entity.getRemarks())
                .set(DataDictionaryValueEntity::getEnabled, entity.getEnabled())
                .set(DataDictionaryValueEntity::getSorted, entity.getSorted())
                .eq(DataDictionaryValueEntity::getId, entity.getId())
                .update();
    }

    /**
     * 检查字典类型是否是系统字典，如果是系统字典则不允许修改、新增
     *
     * @param entity 字典值信息
     */
    private void checkSystemDataDictionary(DataDictionaryValueEntity entity) {
        DataDictionaryEntity oldEntity = dictionaryRepository.selectById(entity.getDictionaryId());
        if (oldEntity == null) {
            throw new RuntimeException("不存在该字典");
        }
        if (oldEntity.getIsSystem()) {
            throw new RuntimeException("系统字典不允许修改");
        }
    }

    @Override
    public void deleteDataDictionaryValue(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteDataDictionaryValue(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public void enabled(String primaryKey, boolean enabled) {
        lambdaUpdate()
                .set(DataDictionaryValueEntity::getEnabled, enabled)
                .eq(DataDictionaryValueEntity::getId, primaryKey)
                .update();
    }
}
